package com.sites.api;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.sites.common.SiteInfo;

import java.util.Date;

public class ApiInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation invocation) {
        //预制返回信息
        Ret ret = Ret.fail();

        Controller controller = invocation.getController();
        //从header中获取时间+随机字符串:timestamp=1656206645964&nonce=7j7744kdc83vwrfmg1qnczpaaxvr5si1
        String secretDate = controller.getHeader("SecretDate");
        //从secretDate中截取时间戳
        String timestamp = secretDate.substring(secretDate.indexOf("=")+1, secretDate.indexOf("&"));
        //时间戳转换成时间
        Date requestTime = new Date(Long.parseLong(timestamp));

        //判断时间戳是否在有效期内
        Long betweenMinute = DateUtil.between(requestTime, new Date(), DateUnit.MINUTE);
        if(betweenMinute > PropKit.getLong("api.betweenMinute")){
            ret.set(SiteInfo.codeKey, "403");
            ret.set(SiteInfo.msgKey, "服务器拒绝请求");
            controller.renderJson(ret);
            return;
        }

        //从header中获取token
        String token = controller.getHeader(SiteInfo.tokenKey);

        //结合秘钥生成token
        String myToken = HashKit.md5(secretDate+PropKit.get("api.privateKey"));
        //进行token验证
        if(!myToken.equals(token)){
            ret.set(SiteInfo.codeKey, "403");
            ret.set(SiteInfo.msgKey, "服务器拒绝请求");
            controller.renderJson(ret);
            return;
        }

        //通过所有验证后继续执行后续请求
        invocation.invoke();
    }
}
